<?php


namespace app\home\controller;


use app\home\service\CodeService;
use app\home\service\TokenService;
use OSS\Core\OssException;
use OSS\OssClient;
class Image
{


    /**
    * 图片上传
    * @param $image
    */
    public function putImage()
    {
        $user_id = TokenService::getUserInfoFromToken('u_id');
        if (is_array($user_id)) return $user_id;
        $file = $_FILES['image']['tmp_name'];
        //可以上传的类型
        $arr_file_type = ['image/png', 'image/jpg', 'image/jpeg'];
        //如果上传的类型 不在配置的类型数组里面
        if (!in_array($_FILES['image']['type'], $arr_file_type)) return CodeService::IMAGE_TYPE;
        if ($_FILES['image']['size'] > 3000000) return CodeService::IMAGE_SIZE_VERIFICATION;//图片需要小于3M
        $date = date('Y-m-d');
        $savename = 'set/' . $date . '_' . uniqid() . '.jpg';
//        $oos        = aliyun('home',$savename,$file);
        Vendor('aliyun-oss.autoload');
        $accessKeyId = config('set.OSS_KEYID');
        $accessKeySecret = config('set.OSS_SECRET');
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = config('set.OSS_ENDPOINT');
        // 存储空间名称
        $bucket = config('set.OSS_BUCKET');
        // 文件名称
        $object = 'home' . "/" . $savename;

        // 由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
        // $filePath = "./Public/abc.jpg";
        $filePath = $file;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
            $data['code'] = 200;
            $data['msg'] = '上传成功';
            $data['url'] = config('set.OSS_FILE_PATH') . '/' . $object;

        } catch (OssException $e) {

            $data['code'] = 201;
            $data['msg'] = '上传失败';
        }
        if ($data['code'] == 200) {
            //删除本地临时文件
            unlink($file);//清除本地路径
        }
        return $data;

    }
}